package com.anjiebang.intercepter;

import cn.jpush.api.utils.StringUtils;
import com.anjiebang.utils.AjbEncryptUtil;
import com.anjiebang.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户拦截器
 * Created by laiyanlin on 2018/4/8.
 */
@Component
public class InterceptUtil {


    @Autowired
    private RedisUtils redisUtils;
    /**
     * 判断请求消息头是否为空
     */
    boolean canPass(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        String os = httpServletRequest.getHeader("os");
        String osVersion = httpServletRequest.getHeader("osVersion");
        String appVersion = httpServletRequest.getHeader("appVersion");
        String serviceVersion = httpServletRequest.getHeader("serviceVersion");
        String cityId = httpServletRequest.getHeader("cityId");
        String token = httpServletRequest.getHeader("token");
        String sign = httpServletRequest.getHeader("sign");
        String timestamp = httpServletRequest.getHeader("timestamp");


        // 判断请求时间是否在10分钟内
        Long times = Long.parseLong(timestamp);
        if(System.currentTimeMillis()/1000 - times > 60*10){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/auth/invalid/");
            return false;
        }

        // 判断签名是否正确AND请求头数据
        if(StringUtils.isEmpty(os) || StringUtils.isEmpty(osVersion) || StringUtils.isEmpty(appVersion) ||
                StringUtils.isEmpty(serviceVersion) || StringUtils.isEmpty(cityId) ||
                StringUtils.isEmpty(token) || StringUtils.isEmpty(sign) || StringUtils.isEmpty(timestamp) || !token.equals(AjbEncryptUtil.genSign(token,timestamp))
                ){
            return false;
        }



       return true;
    }

}
